<?php
// +----------------------------------------------------------------------
// | Cron控制器
// +----------------------------------------------------------------------
// | Since: 2014-09-15 16:02
// +----------------------------------------------------------------------
// | Author: shioujun <shioujun@gmail.com>
// +----------------------------------------------------------------------
namespace Crontab\Controller;

use Think\Controller;

/**
 * Crontab计划任务
 */
class CronController extends Controller
{

    /**
     * [task 执行任务]
     *
     * @return [type] [description]
     */
    public function task()
    {
        $cronModel = M('Crontab');
        $rs = $cronModel->where('status=1')->select();
        echo "start at " . date("H:i:s", time()) . "\n";
        // 获取当前服务器IP
        $curr_ip = getServerIp();
        foreach ($rs as $key => $value) {
            $time = time();
            $expr = trim($value['cron_expr']);
            $ips = trim($value['allow_ip']);
            $ip_flag = false;
            $id = $value['id'];
            
            if ($ips === "*" || $ips === "") {
                $ip_flag = true;
            } else {
                $ips = explode(',', $ips);
                if (in_array($curr_ip, $ips)) {
                    $ip_flag = true;
                }
            }
            
            if ($ip_flag && is_time_cron($time, $expr)) {
                $cmd = $value['command'];
                $php_cli_path = C('PHP_CLI_PATH');
                
                $is_force = $value['is_force'] == 1 ? true : false;
                $type = $value['type'];
                
                // PHP CLI模式
                if ($type == 1) {
                    // 组装命令行字符串
                    $cmd = C('PHP_CLI_PATH') . ' ' . CURR_RUN_FILENAME . ' ' . $cmd;
                    process_execute($cmd, $id, true, $is_force);
                }                 // 其他外部命令模式
                else if ($type == 2) {
                    process_execute($cmd, $id, true, $is_force);
                }                 // 内置函数模式
                else if ($type == 0) {
                    $cmd = "R('" . $cmd . "');";
                    process_execute($cmd . ';', $id, false, $is_force);
                }
            }
        }
        echo "end at " . date("H:i:s", time()) . "\n\n";
    }
}